<template>
  <div style="margin:10px 15px;">
    <div
      style="padding:10px;
        overflow:hidden;
        margin-bottom:10px;
        test-align:center;
        line-height:1;
        background:#fff;
        color:#2d8cf0;
        border-radius:5px;
        border: 1px solid #ddd;"
    >
      设备列表
    </div>
    <div>
      <treeselect
        flattenSearchResults
        name="filter-deviee"
        max-height="500"
        v-model="value"
        placeholder="请选择设备..."
        noOptionsText="该企业下无设备列表！"
        noResultsText="没有搜索到目标设备！"
        noChildrenText="该区域下没有设备！"
        value-consists-of="LEAF_PRIORITY"
        :multiple="false"
        :clearable="true"
        :searchable="true"
        :disabled="false"
        :always-open="true"
        :append-to-body="true"
        :options="treeData"
        @select="handleSelect"
      />
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";
import format from "@/utils/format";
import { getDeviceList as httpGetDevices, getGroupByDevice } from "@/api";
export default {
  props: ["companyId"],
  watch: {
    companyId() {
      this.init();
    }
  },
  computed: {
    ...mapState({
      userRole: state => state.userInfo.rname
    })
  },
  data() {
    return {
      treeData: [],
      value: null
    };
  },
  mounted() {
    this.init();
  },

  methods: {
    async init() {
      const vm = this;
      const { id: deviceId } = vm.$route.params;
      let item = null;
      if (!vm.companyId) return false;
      const params = { companyId: vm.companyId };
      const deviceListData = await httpGetDevices(params);
      const { code: code1, data: data1 } = deviceListData;
      if (code1 === 200 && data1) {
        if (vm.userRole === "ROLE_DEMO") {
          vm.treeData = format.formatTree1(data1.group, data1.device);
        } else {
          vm.treeData = format.formatTree(data1.group, data1.device);
        }
        if (deviceId) {
          const { data: group } = await getGroupByDevice({
            deviceId: deviceId
          });
          const { id: groupId } = group;
          const currentGroup = vm.treeData.find(t => t.id === groupId);
          const currentDevice = currentGroup.children.find(
            t => t.id === deviceId
          );
          if (currentDevice) {
            item = currentDevice;
          }
        } else {
          const canUseGroup = vm.treeData.find(
            t => t.children && t.children.length > 0
          );
          if (canUseGroup) {
            item = canUseGroup.children[0];
          } else {
            vm.$Message.error("当前企业下未录入设备");
          }
        }
        vm.filterText = item.id;
        vm.$emit("on-choose", item);
      } else {
        vm.$Message.error("当前企业下未录入设备");
        vm.treeData = [];
      }
    },

    handleSelect(item) {
      if (item.children) {
        return false;
      } else {
        this.$emit("on-choose", item);
      }
    }
  }
};
</script>
